<template>
	<div class="data-collection">
		<component
			:is="formSlot"
			:confirmText="step === 4 ? '确认' : '下一步'"
			@onSubmit="onSubmit"
			@onCancel="onCancel"
			cancelText="上一步"
			:showCancel="step !== 1"
		>
			<h3>基本信息</h3>
			<component
				:is="baseInfoEdit"
				:initData="initData"
				:houseData="buildingInfo"
        :locationInfo="locationInfo"
        showLocation
			/>
			<component
				:is="baseForm"
				:formData="formData"
				:initData="initData"
				:step="step"
			/>
		</component>
	</div>
</template>

<script setup>
import formSlot from '@/components/formSlot'
import baseInfoEdit from './components/baseInfoEdit'
import baseForm from './components/baseForm'
import { useRouter, useRoute } from 'vue-router'
import { collectionInfo, updateHouse } from '@/service/api'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { useBuildingStore } from '@/store'
import { storeToRefs } from 'pinia'

const route = useRoute()
const router = useRouter()
const buildingStore = useBuildingStore()

const { buildingInfo } = storeToRefs(buildingStore)
const formData = reactive({})
const initData = ref({})
const step = ref(1)

const submitNumberKey = [
	'jzrks',
	'zzrs',
	'jzfjs',
	'fjsl',
	'jzscxyaqcksl',
	'jzscmj',
	'jzszlwxdlgybjqs',
	'jzsyjyplmhxts',
	'jzxyssltsl',
	'mhqsl',
	'fytsmz',
	'bdfwjzrydddzxcsl',
	'sstdsyyrkrclzx',
	'gryssdcsszblyyqksddp',
	'wdwhjgfjgqsyyrkrgbdj',
	'cs',
	'xggdjsbp',
	'sfazzzryslpbfytsmd',
	'ckfhwggptzlsl',
	'cjzwqtjyyt',
	'ywgdlttxwd',
	'sfazfztsss',
	'czryrs'
]
const submitStringKey = [
	'jsrysstd',
	'sstdjsqk',
	'cjzwqtjyytmsg',
	'cdfs',
	'cdfsqtbz',
	'tdsfdb',
	'sfmzstdPhoto', // 疏散通道是否合格 照片
	'sfmzstdMsg',
	'sfmzstdZgqk',  // 疏散通道是否合格 整改情况
	'sfmzstdZgphoto',

	'sfczjxgbczzrPhoto',
	'sfczjxgbczzrMsg',
	'sfczjxgbczzrZgqk', // 屋顶、围护结构=改、房间隔墙使用易燃可燃夹芯彩钢板搭建且出租住人 整改情况
	'sfczjxgbczzrZgphoto', // 屋顶、围护结构=改、房间隔墙使用易燃可燃夹芯彩钢板搭建且出租住人   照片

	'sstdsyyrkrclzxPhoto',
	'sstdsyyrkrclzxMsg',
	'sstdsyyrkrclzxZgqk',
    'sstdsyyrkrclzxZgphoto',

	'gryssdcsszblyyqksddpPhoto',
	'gryssdcsszblyyqksddpMsg',
	'gryssdcsszblyyqksddpZgqk',    // 供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚、雨棚  整改情况
	'gryssdcsszblyyqksddpZgphoto', // 供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚、雨棚  照片

]

const onCancel = () => {
	step.value--
}

const onSubmit = async () => {
	if (step.value !== 4) {
		step.value++
		return
	}
	const params = {
		id: initData.value?.id,
		fwbh: buildingInfo.value.fwbh,
    currentlocation: locationInfo.value?.address,
    longitude: locationInfo.value?.lng,
    latitude: locationInfo.value?.lat,
	}
	submitNumberKey.map(item => {
		params[item] = +formData[item]
	})
	submitStringKey.map(item => {
		params[item] = formData[item]
	})
	if (params.jsrysstd === '已完成') {
		params.sstdjsqk = params.sstdjsqk?.join('|')
	}
	params.cjzwqtjyytmsg = params.cjzwqtjyytmsg?.join('|')
	params.cdfs = params.cdfs?.join('|')
	params.address = initData.value.address
	params.hzxm = initData.value.hzxm

	// 处理照片 url
    params["sfmzstdPhoto"] = params.sfmzstdPhoto?.map(item => {
		return item.url
	})?.join('|')
    params["sfmzstdZgphoto"] = params.sfmzstdZgphoto?.map(item => {
		return item.url
	})?.join('|')
    params["sfczjxgbczzrPhoto"] = params.sfczjxgbczzrPhoto?.map(item => {
		return item.url
	})?.join('|')
    params["sfczjxgbczzrZgphoto"] = params.sfczjxgbczzrZgphoto?.map(item => {
		return item.url
	})?.join('|')

    params["sstdsyyrkrclzxPhoto"] = params.sstdsyyrkrclzxPhoto?.map(item => {
		return item.url
	})?.join('|')
    params["sstdsyyrkrclzxZgphoto"] = params.sstdsyyrkrclzxZgphoto?.map(item => {
		return item.url
	})?.join('|')
    params["gryssdcsszblyyqksddpPhoto"] = params.gryssdcsszblyyqksddpPhoto?.map(item => {
		return item.url
	})?.join('|')
    params["gryssdcsszblyyqksddpZgphoto"] = params.gryssdcsszblyyqksddpZgphoto?.map(item => {
		return item.url
	})?.join('|')
	// 整改情况 数值类型
    params["sfmzstdZgqk"] = +params.sfmzstdZgqk
    params["sfczjxgbczzrZgqk"] = +params.sfczjxgbczzrZgqk
    params["sstdsyyrkrclzxZgqk"] = +params.sstdsyyrkrclzxZgqk
    params["gryssdcsszblyyqksddpZgqk"] = +params.gryssdcsszblyyqksddpZgqk
	// 没有隐患 （选择否的时候） 去掉多余 的  字段
	delFiled(params)
		console.log('delFiled1111',params)
	// confirmSubmit(params)
	sessionStorage.setItem('collentedData', JSON.stringify(params))
	nextTick(() => {
		router.push({
			name: 'inspection-check-form'
		})
	})
}

const delFiled = (params)=>{
	console.log('delFiled',params)
	if(params.tdsfdb === '是'){
        delete params.sfmzstdMsg
        delete params.sfmzstdZgqk
        delete params.sfmzstdZgphoto
	}
    if(params.wdwhjgfjgqsyyrkrgbdj === 0){
        delete params.sfczjxgbczzrMsg
        delete params.sfczjxgbczzrZgqk
        delete params.sfczjxgbczzrZgphoto
	}
    if(params.sstdsyyrkrclzx === 0){
        delete params.sstdsyyrkrclzxMsg
        delete params.sstdsyyrkrclzxZgqk
        delete params.sstdsyyrkrclzxZgphoto
	}
	if(params.gryssdcsszblyyqksddp === 0){
        delete params.gryssdcsszblyyqksddpMsg
        delete params.gryssdcsszblyyqksddpZgqk
        delete params.gryssdcsszblyyqksddpZgphoto
	}
}
const confirmSubmit = async (params) => {
	try {
		const result = await updateHouse(params)
		if (result?.succ) {
			router.push({
				name: 'inspection-check-form'
			})
		}
	} catch (e) {
	}
}

const getCollectInfo = async () => {
	try {
		const result = await collectionInfo({
			id: route?.query?.fwbh || buildingInfo.value.id,
			fwbh: route?.query?.fwbh || buildingInfo.value.fwbh
		})
		if (result?.succ) {
			Object.keys(result?.data)?.forEach(key => {
				initData.value[key] = result.data[key]?.zc ||  result.data[key]
				initData.value[`${key}_diff`] = result.data[key]?.jchc
			})
			submitNumberKey.map(item => {
				formData[item] = (result?.data?.[item]?.zc || result?.data?.[item]?.zc === 0) ? +result?.data?.[item]?.zc : ''
			})
			submitStringKey.map(item => {
				formData[item] = result?.data?.[item]?.zc
			})
			if (result?.data?.jsrysstd?.zc === '已完成') formData.sstdjsqk = result?.data?.sstdjsqk?.zc?.split('|')
			formData.cjzwqtjyytmsg = result?.data?.cjzwqtjyytmsg?.zc?.split('|')
			formData.cdfs = result?.data?.cdfs?.zc?.split('|')
			// 疏散通道是否合格 清除照片、描述 、 整改情况、整改照片
			formData.sfmzstdPhoto = []
			formData.sfmzstdMsg = ''
            formData.sfmzstdZgqk = ''
            formData.sfmzstdZgphoto = []

			// 屋顶、围护结构=改、房间隔墙使用易燃可燃夹芯彩钢板搭建且出租住人
			formData.sfczjxgbczzrPhoto = []
			formData.sfczjxgbczzrMsg = ''
			formData.sfczjxgbczzrZgqk = ''
            formData.sfczjxgbczzrZgphoto = []

			// 疏散通道使用易燃可燃材料装修
			formData.sstdsyyrkrclzxPhoto = []
			formData.sstdsyyrkrclzxMsg =  ''
			formData.sstdsyyrkrclzxZgqk = ''
            formData.sstdsyyrkrclzxZgphoto = []

			// 供人员疏散的场院、内院、天井设置不利于烟气扩散的顶棚、雨棚
			formData.gryssdcsszblyyqksddpPhoto = []
			formData.gryssdcsszblyyqksddpMsg = ''
			formData.gryssdcsszblyyqksddpZgqk = ''
            formData.gryssdcsszblyyqksddpZgphoto = []

		}
	} catch (e) {
       // 错误处理
	}
}


const locationInfo = ref({
  address: null,
  lat: null,
  lng: null,
});

const getLocation = async () => {
  AMap.plugin('AMap.Geolocation', function() {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, // 是否使用高精度定位，默认：true
      timeout: 10000, // 设置定位超时时间，默认：无穷大
      offset: [10, 20],  // 定位按钮的停靠位置的偏移量
      zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      position: 'RB' //  定位按钮的排放位置,  RB表示右下
    })

    geolocation.getCurrentPosition(function (status, result) {
      console.log('获取地址', status, result)
      if (status === 'complete') {
        locationInfo.value = {
          address: result?.formattedAddress || result?.regeocode?.formattedAddress,
          lat: result?.position?.lat,
          lng: result?.position?.lng,
        }
        // 若定位未获取地址信息 但是获取到经纬度 则调用逆地理解析获取地址
        if (!result?.formattedAddress && !result?.regeocode?.formattedAddress) {
          getAddressByLngLat()
        }
      }
    })
  })
}

const getAddressByLngLat = () => {
  var geocoder = new AMap.Geocoder({
    city: '010', //城市设为北京，默认：“全国”
    radius: 1000 //范围，默认：500
  })
  geocoder.getAddress([locationInfo.value.lng, locationInfo.value.lat], function(status, result) {
    console.log('逆地理解析', status, result)
    if (status === 'complete' && result.regeocode) {
      locationInfo.value = {
        ...locationInfo.value,
        address: result.regeocode.formattedAddress,
      }
    }
  });
}

onMounted( () => {
  getLocation()
	getCollectInfo()
})
</script>

<style scoped lang="less">
.data-collection {
	height: 100%;
	:deep(h3) {
		padding: 20px 32px;
		position: relative;
		text-indent: 10px;
		&:before {
			position: absolute;
			content: '';
			height: 35%;
			top: 50%;
			transform: translateY(-50%);
			width: 6px;
			border-radius: 3px;
			left: 30px;
			background: var(--van-primary-color);
		}
	}
	:deep(.van-form) {
		.van-cell {
			.van-field__label {
				width: 470px;
			}
		}
	}
}
</style>
